package com.glela.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.glela.api.pay.yeepay.component.YeePay;
import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.constant.BaseRestrictionsEnum;
import com.glela.common.constant.CommonConstants;
import com.glela.common.constant.KeepAccountsTypeConstants;
import com.glela.common.constant.PayTypeEnum;
import com.glela.common.constant.StoreTypeEnum;
import com.glela.common.service.SMSService;
import com.glela.common.util.DateUtil;
import com.glela.common.util.StringUtil;
import com.glela.company.model.XzOmsLog;
import com.glela.company.service.XzOmsLogService;
import com.glela.order.dao.OrderDao;
import com.glela.order.mapper.OrderDetailMapper;
import com.glela.order.mapper.OrderInfoMapper;
import com.glela.order.mapper.OrderObjectMapper;
import com.glela.order.mapper.OrderSettlementCommisionMapper;
import com.glela.order.model.Commision;
import com.glela.order.model.LogisticsStatus;
import com.glela.order.model.OrderInfo;
import com.glela.order.model.OrderObject;
import com.glela.order.model.OrderPay;
import com.glela.order.model.OrderSettlementCommision;
import com.glela.order.model.logisticsDetail;
import com.glela.order.model.response.OrderObjectVo;
import com.glela.order.service.LogisticsStatusService;
import com.glela.order.service.OrderInfoService;
import com.glela.order.service.OrderObjectService;
import com.glela.order.service.OrderPayService;
import com.glela.order.service.OrderService;
import com.glela.order.service.OrderStatusService;
import com.glela.order.service.impl.NotifyWxMsgServiceImpl;
import com.glela.platform.mapper.OperationLogMapper;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.CUserPointTransaction;
import com.glela.platform.model.OperationLog;
import com.glela.platform.model.User;
import com.glela.platform.model.UserJournal;
import com.glela.platform.model.UserPointJournal;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.OperationLogService;
import com.glela.platform.service.UserService;
import com.glela.statistics.service.UserEarningsService;
import com.glela.talent.util.MyDateUtil;

/**
 * @author liujie
 * @2016年10月28日
 */
@Component
public class OrderTask {
	private static final Logger logger = LoggerFactory.getLogger(OrderTask.class);

	@Resource(name = "orderService2")
	private OrderService orderService2;
	@Autowired
	private NotifyWxMsgServiceImpl	notifyWxMsgServiceImpl;

	/** MaoZeYao **/
	@Autowired
	private OrderObjectMapper orderObjectMapper;
	@Autowired
	private OrderInfoMapper orderInfoMapper;
	@Autowired
	private OrderDetailMapper orderDetailMapper;
	@Autowired
	private XzOmsLogService xzOmsLogService;
	@Autowired
	private OrderStatusService orderStatusService;
	@Autowired
	private OrderObjectService	orderObjectService;
	@Autowired
	protected OrderDao orderDao;
	@Autowired
	OrderPayService				orderPayService;
	@Autowired
	private UserService		userService;
	@Autowired
	private OrderSettlementCommisionMapper	orderSettlementCommisionMapper;
	@Autowired
	private OperationLogService 	operationLogService;
	@Autowired
	private RedisUtil	redisUtil;
	@Autowired
	private OrderInfoService	orderInfoService;
	@Autowired
	private BaseRestrictionsService	baseRestrictionsService;
	@Autowired
	private SMSService	smsService;
	@Autowired
	private OperationLogMapper	operationLogMapper;
	@Autowired
	private LogisticsStatusService	logisticsStatusService;
	@Autowired
	protected YeePay yeePay;
	private MyDateUtil util = MyDateUtil.INSTANCE;
	@Autowired
	protected UserEarningsService userEarningsService;
	/**
	* 取消订单
	* @author gaoweiqi
	* @date 2017年10月20日 17:00:00
	*
	**/
	public void autoCancelOrder() {
		logger.info("-------->autoCancelOrder------->Start");
		//获取可取消的订单 取消时间限定由配置表ID=13决定
		List<OrderObject> objList = orderObjectMapper.selectOrderObjectByStatusAndPageLimit();
			for (OrderObject orderObject : objList) {
				try {
				getOrderService().editCancelOrderByOrderId(orderObject.getId(), orderObject.getUserId());
				} catch (Exception e) {
					logger.error("取消订单错误,订单ID:"+orderObject.getId()+" " , e.getMessage() , e );
				}
			}
	}
	/**
	 * 处理订单支付回调任务
	 * @author gaoweiqi
	 * @date 2017年12月09日 21:30:00
	 *
	 **/
	public void updatePayOrder() {
		List<OrderSettlementCommision> list= 
				orderSettlementCommisionMapper.selectByStatusLimitNumber(2,100);
		for(OrderSettlementCommision temp:list){
			try {
				int i=orderSettlementCommisionMapper.updateStatus("",3, 2, 
								DateUtil.getNow(), temp.getId());//正在处理
				logger.warn("订单:{} 开始处理状态{}{}{}", temp.getOrderSn(),3,2,i);
				if(i==0){continue;}
				boolean sendSMS=orderService2.addOrder_settlement_commision(temp.getOrderSn());//计算单处理完 开始进队列
				if(sendSMS){
					//发送微信模版消息-推荐销售成功 
					notifyWxMsgServiceImpl.sendWxTemplateMsgMarketingSuccess(temp.getOrderObjectId());
					//发送下单短信
					OrderObject objorder = orderService2.selectOrderObjectByOrderSn(temp.getOrderSn());
					if (objorder.getOpenStoreUserId() != null) {// 有店中店用户 判断是不是店主  如果是店主就发短息
						ResponseUser OpenStoreUser = userService.selectUserRoleById(objorder.getOpenStoreUserId());
						if (OpenStoreUser != null&& ArrayUtils.contains(new int[] {3,4,7,11},OpenStoreUser.getRoleId())) {// 是店主 发短信
							ResponseUser PayOrderUser = userService.selectUserRoleById(objorder.getUserId());
							if (PayOrderUser != null&& !StringUtils.isAnyBlank(PayOrderUser.getUserName(),OpenStoreUser.getUserName())) {// 准备短信内容
								BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache(
										BaseRestrictionsEnum.PAY_ORDER_SMS.getText());
								if (baseRestrictions != null&& baseRestrictions.getStatus() == 1) {// 需要发送短信
									List<OrderInfo> listorderinfo = orderInfoService.selectOrderInfoByOrderObjectIdC(objorder.getId());
									for (OrderInfo orderInfo : listorderinfo) {
										// PayOrderPhone在你的小铺下单啦！订单编号:orderSn【小铺来了】
										String SMS = baseRestrictions.getName().replace(
											"PayOrderPhone",StringUtil.replaceChars(3, 2,PayOrderUser.getUserName()))
											.replace("orderSn",orderInfo.getOrderSn())
										.replace("amount",String.valueOf((orderInfo.getCommisionFee()+orderInfo.getPointFee())/100.0));
										Long responseSMS = smsService.sendMsgJianZhou(
												false, OpenStoreUser.getUserName(), SMS);// 立即发送短信
										if (responseSMS < 0) {
											logger.error("下单发送短信失败：下单人：{}，短信接收人:{}",
													PayOrderUser.getUserName(),
													OpenStoreUser.getUserName());
										}
										// 短信日志
										OperationLog log = new OperationLog();
										log.setObjId(OpenStoreUser.getUserId().intValue());
										log.setObjName(String.valueOf(OpenStoreUser.getNickName()));
										log.setModule("PayOrderCallOpenStoreUser");
										log.setOperateType("sendSms");
										Long createLongTime = ((new Date().getTime()) / 1000);
										log.setCreatedAt(createLongTime.intValue());
										log.setDescription("下单短信提醒" + SMS);
										operationLogService.saveOperateLog(log);
									}
								}
							}
						}
					}
				}
			} catch (Exception e) {
				orderSettlementCommisionMapper.updateStatus(
		e.getMessage().length()>100?e.getMessage().substring(0, 100):e.getMessage(),5,
				orderSettlementCommisionMapper.selectByorderSn(temp.getOrderSn()).getStatus(), 
				DateUtil.getNow(), temp.getId());
				logger.error("定时任务生成计算单失败：{}",e);
			}
		}
	}
 
	/**
	 * 新版自动完成订单
	 * @author gaoweiqi
	 * @date 2018年01月30日 21:30:00
	 *
	 **/
	public void autoCompilteOrder() {
			List<OrderInfo> orderInfoList = orderInfoMapper.selectOrderInfoIdByStatusThree();
			for (OrderInfo orderInfo : orderInfoList) {
				orderStatusService.confirmOrder(orderInfo.getOrderSn());
			}
		logger.info("-------------->本次订单自动完成数据处理完成 处理数量:{}",orderInfoList!=null?orderInfoList.size():0);
	}
	
	/**
	 * 自动关闭评论 4 订单已完成 0可评论
	 */
	public void autoCloseOrderComment() {
		logger.info("--------autoCloseOrderComment start---------");
		try {
			int page = 1;
			int pageSize = 1000;
			int startIndex = (page - 1) * pageSize;
			boolean flag = true;
			int commentCloseDay = 7; // 暂定时间
			// List<OrderObject> objList =
			// orderObjectMapper.selectOrderObjectByStatusAndCommontStatus(4,0);

			while (flag) {
				List<OrderObject> objList = orderObjectMapper.selectOrderObjectByStatusAndCommontStatus(4, 0,
						startIndex, pageSize);
				if (objList.size() <= 0) {
					flag = false;
				}
				if (flag) {
					for (OrderObject orderObject : objList) {
						if (DateUtil.betweenTime(orderObject.getUpdateTime(), util
								.getAccurateDays(orderObject.getUpdateTime(), commentCloseDay)) == commentCloseDay) {
							// 正常处理方式
							int orderObjectUpdateStatus = orderObjectMapper
									.updateOrderObjectToCommentSuccess(orderObject.getId());
							if (orderObjectUpdateStatus <= 0) {
								logger.error("------>父订单操作异常");
							}

							int orderInfoUpdateStatus = orderInfoMapper
									.updateOrderInfoToCommentByOrderObjectId(orderObject.getId());
							if (orderInfoUpdateStatus <= 0) {
								logger.error("------>子订单评论已关闭");
								throw new Exception();
							}

							int updateOrderDetailStatus = orderDetailMapper
									.updateOrderDetailToCommentSuccessByOrderObjectId(orderObject.getId());
							if (updateOrderDetailStatus <= 0) {
								logger.error("------>订单详情评论已关闭");
								throw new Exception();
							}
							logger.info("------>父订单:" + orderObject.getOrderSn() + "所属评论已关闭");
						}
					}
					startIndex = (++page - 1) * pageSize;
				}
			}
			logger.info("-------------->本次关闭评论数据处理完成");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		logger.info("--------autoCloseOrderComment end---------");
	}

	/**
	 * 自动分佣接口
	 * 
	 * @author gaoweiqi
	 * @date 2018年01月21日 12:44:05 订单为单位进行分佣
	 **/
	public void autoOrderCommision() {
		// 分佣
		logger.info("--------autoOrderCommision start---------");
		// 获取可分佣交易单
		List<OrderObject> orderObjList = orderService2.selectOrderObjectForCommision();
		if (orderObjList == null || orderObjList.size() == 0) {
			return;
		}
		// 根据可分佣交易单查找可分佣子订单
		List<OrderInfo> orderInfoList = orderService2.selectOrderInfoInOOIdForCommision(orderObjList);
		Map<Long, OrderInfo> orderInfoIDMap = new HashMap<Long, OrderInfo>();
		Map<String, OrderInfo> orderInfoSNMap = new HashMap<String, OrderInfo>();
		for (OrderInfo orderInfo : orderInfoList) {
			orderInfoIDMap.put(orderInfo.getId(), orderInfo);
			orderInfoSNMap.put(orderInfo.getOrderSn(), orderInfo);
		}
		// 定义一个单独的用户集合来保存查询过的用户信息
		Map<Long, User> UserMap = new HashMap<Long, User>();// 用户集合
		// 以订单为单位处理余额事务和妆币事务
		for (OrderObject OrderObj : orderObjList) {
			try {
				Map<String, Map<Long, Integer>> earningsMap = new HashMap<String, Map<Long, Integer>>();// 收益 <订单号,<用户id，收益>>
				List<OrderObject> orderObjectListTemp = new ArrayList<OrderObject>();
				orderObjectListTemp.add(OrderObj);
				List<UserJournal> userJournalList = new ArrayList<UserJournal>();// 佣金流水
				List<UserPointJournal> userPointJournalList = new ArrayList<UserPointJournal>();// 积分流水
				// 根据可分佣交易单查找未处理分佣明细
				List<Commision> commisionList = orderService2.selectInOrderObjectIdForCommision(orderObjectListTemp);
				// 根据可分佣交易单查找未处理积分明细
				List<CUserPointTransaction> PointTransactionList = orderService2.selectInOrderObjectIdForPoint(orderObjectListTemp);
				// 根据余额事务集合生成流水信息
				for (Commision commision : commisionList) {
					if (orderInfoIDMap.get(commision.getOrderInfoId()) == null) {
						logger.error("---orderInfoId---数据异常" + commision.getOrderInfoId());
						continue;
					}
					String KeepAccountsType = "";
					// 获取佣金的账务类型
					if (orderInfoIDMap.get(commision.getOrderInfoId()).getStoreId().intValue() == StoreTypeEnum.T14.getCode()) {
						KeepAccountsType = KeepAccountsTypeConstants.COMMISSION_SKIN79;
					} else {
						KeepAccountsType = KeepAccountsTypeConstants.COMMISSION_NOSKIN79;
					}
					// 封装分佣流水
					UserJournal userJournal = new UserJournal();
					userJournal.setUserId(commision.getUserId());
					userJournal.setOrderSn(orderInfoIDMap.get(commision.getOrderInfoId()).getOrderSn());
					userJournal.setPromotionDetailId(orderInfoIDMap.get(commision.getOrderInfoId()).getPromotionId());
					userJournal.setMoney(commision.getFee());
					userJournal.setType(CommonConstants.USER_JOURNAL_TYPE_ADD);
					userJournal.setBankId(0);
					userJournal.setStatus(2);
					userJournal.setComment(commision.getComment());
					userJournal.setBusinessTypeId(commision.getBusinessTypeId());
					userJournal.setBusinessTypeName(commision.getBusinessTypeName());
					userJournal.setIsDelete(0);
					userJournal.setCommisionId(commision.getId().intValue());
					userJournal.setKeepAccountsType(KeepAccountsType);
					userJournal.setExtend3(commision.getExtend3());
					userJournalList.add(userJournal);
					// 保存当前分佣人信息
					if (UserMap.get(commision.getUserId()) == null) {
						User CommisionUser = userService.getUser(commision.getUserId());
						if (CommisionUser != null && StringUtils.isNotBlank(CommisionUser.getUserName())) {
							UserMap.put(commision.getUserId(), CommisionUser);
						}
					}
					if (commision.getFee().intValue() > 0 && orderInfoIDMap.get(commision.getOrderInfoId()) != null && orderInfoSNMap.get(orderInfoIDMap.get(commision.getOrderInfoId()).getOrderSn()) != null) {
						OrderInfo info = orderInfoSNMap.get(orderInfoIDMap.get(commision.getOrderInfoId()).getOrderSn());
						// 计算个人所得分佣
						if (earningsMap.get(info.getOrderSn()) == null) {
							Map<Long, Integer> Map = new HashMap<Long, Integer>();
							Map.put(commision.getUserId(), commision.getFee());
							earningsMap.put(info.getOrderSn(), Map);
						} else {
							Map<Long, Integer> Map = earningsMap.get(info.getOrderSn());
							if (Map.get(commision.getUserId()) == null) {
								Map.put(commision.getUserId(), commision.getFee());
							} else {
								Map.put(commision.getUserId(), Map.get(commision.getUserId()) + commision.getFee());
							}
						}
					}
				}
				// 根据妆币事务生成妆币流水
				for (CUserPointTransaction pointTransaction : PointTransactionList) {
					UserPointJournal pointJournal = new UserPointJournal();
					String KeepAccountsType = "";
					// 获取佣金的账务类型
					if (orderInfoSNMap.get(pointTransaction.getOrderSn()).getStoreId().intValue() == StoreTypeEnum.T14.getCode()) {
						KeepAccountsType = KeepAccountsTypeConstants.POINT_SKIN79;
					} else {
						KeepAccountsType = KeepAccountsTypeConstants.POINT_NOSKIN79;
					}
					pointJournal.setValueByPointTransaction(pointTransaction);// 积分事务到积分记录表
					pointJournal.setBusinessSourceId(pointTransaction.getId());// 业务源单ID
					pointJournal.setKeepAccountsType(KeepAccountsType);// 财务记账类型
					userPointJournalList.add(pointJournal);
					// 保存当前积分获得人信息
					if (UserMap.get(pointTransaction.getUserId()) == null) {
						User pointUser = userService.getUser(pointTransaction.getUserId());
						if (pointUser != null && StringUtils.isNotBlank(pointUser.getUserName())) {
							UserMap.put(pointTransaction.getUserId(), pointUser);
						}
					}
					if (pointTransaction.getAmount() != null && pointTransaction.getAmount() > 0 && orderInfoSNMap.get(pointTransaction.getOrderSn()) != null) {
						OrderInfo info = orderInfoSNMap.get(pointTransaction.getOrderSn());
						// 计算个人所得分佣
						if (earningsMap.get(info.getOrderSn()) == null) {
							Map<Long, Integer> Map = new HashMap<Long, Integer>();
							Map.put(pointTransaction.getUserId(), pointTransaction.getAmount().intValue());
							earningsMap.put(info.getOrderSn(), Map);
						} else {
							Map<Long, Integer> Map = earningsMap.get(info.getOrderSn());
							if (Map.get(pointTransaction.getUserId()) == null) {
								Map.put(pointTransaction.getUserId(), pointTransaction.getAmount().intValue());
							} else {
								Map.put(pointTransaction.getUserId(), Map.get(pointTransaction.getUserId()) + pointTransaction.getAmount().intValue());
							}
						}
					}
				}
				orderService2.autoCommision(commisionList, userJournalList, PointTransactionList, userPointJournalList, orderObjectListTemp);
				logger.info("--------autoOrderCommision end---------");
				// 插入redis 准备发送短息给用户 由定时任务处理
				// 尊敬的用户 订单P11111的123佣金和222积分已经到账 请注意查收
				if (earningsMap.size() > 0) {// 有收益开始拼接信息 总收益大于0 插入redis中准备执行
					for (String orderinfoSn : earningsMap.keySet()) {
						StringBuilder MSG = new StringBuilder();
						MSG.append(orderinfoSn).append("|");
						for (Long userId : earningsMap.get(orderinfoSn).keySet()) {
							User u = UserMap.get(userId);
							MSG.append(u.getUserName()).append("=").append((earningsMap.get(orderinfoSn).get(userId).doubleValue() / 100)).append("|");
						}
						redisUtil.sadd(RedisKeys.YG_ToAccount_SMS, MSG.toString());
					}
				}
			} catch (Exception e) {
				logger.error("--------autoOrderCommision error-------objSN:" + OrderObj.getOrderSn());
				logger.error(e.getMessage(), e);
			}
		}

	}

	/**
	 * <dl>
	 * <dt>查询未处理分账信息</dt>
	 * @Scheduled(cron = "0 0/2 * * * ? ")//每两分钟触发一次
	 * @Scheduled(cron = "0 0 0 * * ?")//每天晚上12点触发一次
	 * </dl>
	 * @author gaoweiqi
	 * @date 2017年8月29日 12:44:05
	 */
	public void selfEliminate() {
		List<String> listString = getOrderService().selectOrderClearing();//查询未处理的分账
		for (String orderSn : listString) {
			if (orderSn == null) {
				continue;
			}
			try {
				getOrderService().divide(orderSn);
			} catch (Exception e) {
				logger.error("订单[{}]分账异常：{}", orderSn, e.getMessage(), e);
			}
		}
	}

	/**
	 * 自动推送
	 * 
	 * @throws Exception
	 */
	public void selfMotionPush() {
		List<String> listString = xzOmsLogService.selectAutoPushOrder();
		for (String orderSn : listString) {
			try {
				OrderObjectVo orderObjectVo = orderObjectService.getOrderObjectEntityByOrderSnTwo(orderSn);
				if (orderObjectVo.getPayType().intValue() == 0) {
					orderObjectVo.setPayType(PayTypeEnum.T23.getCode());
				}
				String t_id = null;
				List<OrderPay> selectSuccess = orderPayService.selectSuccess(orderObjectVo.getOrderSn());
				if (CollectionUtils.isEmpty(selectSuccess) && !StringUtils.equals(orderObjectVo.getOrderSn(), orderObjectVo.getPayId())) {
					logger.error("订单[{}]无支付成功记录", orderSn);
					continue;
				} else if (selectSuccess.size() > 1) {
					logger.error("订单[{}]有{}条支付成功记录：{}", orderSn, selectSuccess.size(), JSONObject.toJSONString(selectSuccess));
					continue;
				} else if (selectSuccess.size() == 1) {
					t_id = selectSuccess.get(0).getPaySn();
				} else {
					t_id = orderObjectVo.getOrderSn();
					logger.warn("订单[{}]为0元付订单", orderSn);
				}
//				getOrderService().divide(orderObjectVo.getOrderSn());
				getOrderService().updateOrderForXZOMS(orderObjectVo.getOrderSn(), orderObjectVo.getPayId(), orderObjectVo.getPayType(), t_id);
				orderObjectVo = null;
				selectSuccess = null;
				t_id = null;
			} catch (Exception e) {
				logger.error("订单[{}]推送OMS异常：{}", orderSn, e.getMessage(), e);
				xzOmsLogService.deleteByPrimaryOrderSn(orderSn);
				XzOmsLog xzOmsLog = new XzOmsLog();
				xzOmsLog.setOrderSn(orderSn);
				xzOmsLog.setOrderInfoSn(null);
				xzOmsLog.setResult(StringUtils.substring(e.getMessage(), 0, 25));
				xzOmsLogService.insertSelective(xzOmsLog);
			}
		}
	}

	/**
	 * <dl>
	 * <dt>定时发送短信{佣金到账信息}</dt>
	 * 
	 * @Scheduled(cron = "0 0 9 * * ?")//每天早上9点触发一次
	 *                 </dl>
	 * @author gaoweiqi
	 * @date 2018年01月24日 12:44:05
	 */
	public void sendCommisionMS() {
		String orderSn = "";
		// 发送短信
		BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.COMMISSION_TO_ACCOUNT_SMS.getText());
		if (baseRestrictions != null && baseRestrictions.getStatus() == 1) {// 需要发送短信
			List<String> MSGs = redisUtil.srandmember(RedisKeys.YG_ToAccount_SMS, redisUtil.scard(RedisKeys.YG_ToAccount_SMS).intValue());
			for (String MSG : MSGs) {
				try {
					Map<String, String> SMSmap = parseMSG(MSG);
					orderSn = parseOrderSn(MSG);
					if (StringUtils.isNotBlank(orderSn) && MapUtils.isNotEmpty(SMSmap)) {
						for (String str : SMSmap.keySet()) {
							String SMS = baseRestrictions.getName().replace("amount", SMSmap.get(str)).replace("orderSn", orderSn);
							smsService.sendMsgJianZhou(true, str, SMS);
							// 发送佣金到账微信通知
							notifyWxMsgServiceImpl.sendWxTemplateMsgCommissionArrival(str, SMSmap.get(str));
							// 短信日志
							OperationLog log = new OperationLog();
							log.setObjName(String.valueOf(str));
							log.setModule("CommissionToAccount");
							log.setOperateType("sendSms");
							Long createLongTime = ((new Date().getTime()) / 1000);
							log.setCreatedAt(createLongTime.intValue());
							log.setDescription("佣金到账短信提醒" + "收件人  " + str + " 短信内容：" + SMS);
							operationLogMapper.insert(log);
						}
					}
				} catch (Exception e) {
					logger.error("发送短信错误：{}", e.getMessage());
				}
			}
			// 删除key
			redisUtil.del(RedisKeys.YG_ToAccount_SMS);
		}
	}
	private OrderService getOrderService() {
		return orderService2;
	}
	protected Map<String, String> parseMSG(String MSG) throws Exception {
		Map<String, String> userEarnings = new HashMap<String, String>();
		String[] strs = StringUtils.split(MSG, "|");
		for (int i = 1; i < strs.length; i++) {
			String[] innerTemp = StringUtils.split(strs[i], "=");
			if (StringUtils.isNotBlank(innerTemp[0])&&innerTemp[0].length()==11) {
				userEarnings.put(innerTemp[0], innerTemp[1]);
			}
		}
		return userEarnings;
	}
	protected String parseOrderSn(String MSG) throws Exception {
		String[] strs = StringUtils.split(MSG, "|");
		return strs[0];
	}

	/**返回物流签收时间
	 * @param OrderInfo
	 * @return
	 */
	protected String confirmOrderSn(OrderInfo OrderInfo){
		String orderInfoSn=OrderInfo.getOrderSn();
		try {
			//查看订单的物流信息
			LogisticsStatus  logisticsStatus=logisticsStatusService.getLogisticsPojo(orderInfoSn);
			if(logisticsStatus==null){
				logger.info("未查到物流信息 订单号:{}",orderInfoSn);
				return null;
			}
			if(logisticsStatus.getIsFinish()!=null&&logisticsStatus.getIsFinish()!=1){//订单没有被签收
				logger.info("订单还没有被签收 订单号:{}",orderInfoSn);
				return null;
			}
			//设置收货时间 begin
			List<logisticsDetail> list=JSONObject.parseArray(
				JSONObject.parseObject(logisticsStatus.getLogisticsSessage()).get("list").toString(), logisticsDetail.class);
			orderDao.updateConfirmTime(OrderInfo.getId(),list.get(list.size()-1).getDatetime());
			//设置收货时间 end
			return list.get(list.size()-1).getDatetime();
		} catch (Exception e) {
			logger.error("订单确认收货失败 订单号:{} {}",orderInfoSn,e);
			e.printStackTrace();
			return null;
		}
	}
}
